
namespace Behemoth.SharePoint.Utilities {

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Xml;

    using Microsoft.SharePoint;

	public class CleanupTools {

		public static List<FieldCleanupInfo> GetInvalidFields( string webUrl ) {
			List<FieldCleanupInfo> fields = null;
			using (SPSite site = new SPSite( webUrl )) {
				using (SPWeb web = site.OpenWeb()) {
					fields = GetInvalidFields( web, fields, true );
				}
			}
			return fields;
		}
		public static List<FieldCleanupInfo> GetInvalidFields( SPWeb web, List<FieldCleanupInfo> fields, bool recurseSubWebs ) {
			if (fields == null)
				fields = new List<FieldCleanupInfo>();

			string schema = web.Fields.SchemaXml;
			XmlDocument xDoc = new XmlDocument();
			xDoc.LoadXml( schema );
			XmlNodeList xmlFields = xDoc.SelectNodes( "//Fields/Field" );
			for (int i = 0; i < web.Fields.Count; i++) {
				try {
					string name = web.Fields[i].StaticName;
				} catch (SPException ex) {
					FieldCleanupInfo fi = new FieldCleanupInfo();
					fi.Index = i;
					fi.Exception = ex;
					fi.Xml = (XmlElement)xmlFields[i];
					fi.SetProps();
					fields.Add( fi );
				}
			}
			if (recurseSubWebs) {
				foreach (SPWeb subWeb in web.Webs) {
					fields = GetInvalidFields( subWeb, fields, recurseSubWebs );
                    subWeb.Dispose();
				}
			}
			return fields;
		}

	}


	public class FieldCleanupInfo {
		public int Index;
		public XmlElement Xml;
		public Exception Exception;
		public string Name;
		public string Title;

		public void SetProps() {
			Title = Xml.GetAttribute( "DisplayName" );
			Name = Xml.GetAttribute( "Name" );
		}

	}

}
